import React, {
    Component,
} from 'react';
import LinearGradient from 'react-native-linear-gradient';
import {
    StyleSheet,
    Text,
    View,
    Platform,
    Dimensions,
    TouchableOpacity,
    Image,
    StatusBar,
    NativeModules,
    ScrollView,
    Switch, DeviceEventEmitter, ActivityIndicator,
    ToastAndroid,
    Clipboard,
    Alert,
    FlatList,
    TextInput
} from 'react-native';

import moment from 'moment';
import HttpUtils from '../../utils/HttpUtils';
import HttpUrls from '../../utils/HttpUrls';
import AndroidModule from "../../utils/AndroidConnent";
import { ToastToUser } from "../../utils/CustomToast";
import Constant from '../../utils/Constant'
import NoData from '../../utils/NoData'
import Header from '../../components/header';
import { getImgUrl } from '../../utils/ComFunction';
import FoursAlertTexttFieldPop from './FoursAlertTexttFieldPop'


const isIos = Platform.OS == 'ios';
const screenW = Dimensions.get('window').width;
let navigation


let pageSize = 20
let pageNo = 1;
let itemNo = 0;

export default class FoursCarSelectPage extends Component {
    constructor(props) {
        super(props);
        this.state = {
            dataArray: [],
            isRefresh: false,
            showFoot: 0, // 控制foot， 0：隐藏footer  1：已加载完成,没有更多数据   2 ：显示加载中
            showFoursAlertTexttFieldPop: false,
            insertItem: {}
        }
    }

    componentDidMount() {
        this.getCarList(true)
    }

    render() {
        navigation = this.props.navigation;
        return (
            <View style={styles.container}>
                <Header navigation={navigation} Title={'车辆选择'} />

                {this.renderList()}

                {
                    this.state.showFoursAlertTexttFieldPop?
                    <FoursAlertTexttFieldPop
                        onSelected={(value) => {
                            this.setState({
                                showFoursAlertTexttFieldPop: false
                            }, function() {
                                this.insertVcode(value)
                            })
                        }}
                        onClose={() => {
                            this.setState({
                                showFoursAlertTexttFieldPop: false
                            })
                        }}
                        />
                        :
                        null
                }

            </View>
        )
    }

    renderList() {
        return (
            <View style={{ flex: 1 }}>
                <FlatList
                    data={this.state.dataArray}
                    renderItem={this.renderItemView.bind(this)}
                    extraData={this.state}
                    // ListHeaderComponent={this.renderHeader.bind(this)}
                    ListFooterComponent={this.renderFooter.bind(this)}
                    onEndReached={this._onEndReached.bind(this)}
                    onEndReachedThreshold={0.2}
                    onRefresh={this.refreshData}
                    refreshing={this.state.isRefresh}
                    ListEmptyComponent={this.renderEmpty.bind(this)}
                />
            </View>
        )
    }

    renderItemView({ item, index }) {
        return (
            <View>
                <TouchableOpacity
                key={index}
                style={styles.itemContain}
                onPress={() => {
                    if (item.value.vcode) {
                        if (this.props.route.params.completion) {
                            this.props.route.params.completion(item.value)
                        }
                    } else {
                        this.setState({
                            insertItem: item.value,
                            showFoursAlertTexttFieldPop: true
                        })
                    }
                }}
                activeOpacity={0.8}
            >
                {
                    item.value.mainPic ?
                    <Image style={styles.carImg} source={{uri: getImgUrl(item.value.mainPic)}}/>
                    :
                    <Image style={styles.carImg} source={require('source/image/comm/sc_default.png')}/>
                }

                <View style={styles.rightItemBox}>
                    <Text style={styles.brandText}>{item.value.brandName+' '+item.value.seriesName}</Text>
                    <Text style={styles.dateText}>{item.value.purchaseDate+' | '+(item.value.mileage/10000).toFixed(2)+'万公里'}</Text>
                    {
                        item.value.vcode ?
                        <Text style={styles.vinText}>{'VIN码：'+item.value.vcode}</Text>
                        :
                        <Text style={styles.vin1Text}>{'VIN：暂无VIN码'}</Text>
                    }
                    
                </View>
                
            </TouchableOpacity>
            </View>
        )
    }

    renderEmpty() {
        if (!this.state.isRefresh) {
            return (
                <NoData Desc="暂无数据" style={{ marginTop: gREM(200) }} />
            )
        } else {
            return (
                null
            )
        }
    }

    renderHeader() {
        return (
            <View style={styles.header}>
            </View>
        );
    }

    renderFooter() {
        if (this.state.showFoot === 1) {
            return <View style={{ height: Constant.bottomHeight }} />;
        } else if (this.state.showFoot === 2) {
            return (
                <View style={styles.footer}>
                    <ActivityIndicator size="small" color="#999999" />
                    <Text style={styles.loadMoreTextStyle}>正在加载更多数据...</Text>
                </View>
            );
        } else if (this.state.showFoot === 0) {
            return null;
        }
    }

    refreshData = () => {
        this.getCarList(true);
    }

    _onEndReached() {
        if (this.state.dataArray.length == 0) {
            return;
        }
        //如果是正在加载中或没有更多数据了，则返回
        if (this.state.showFoot != 0) {
            return null;
        }

        //底部显示正在加载更多数据
        this.setState({ showFoot: 2 });

        this.getCarList(false);
    }

    getCarList(refresh) {
        if (refresh) {
            pageNo = 1;
            itemNo = 0;
            this.setState({ isRefresh: true })
        } else {
            pageNo++;
        }

        let param = {
            pageNo: pageNo,
            pageSize: pageSize,
            merchantId: Constant.userInfo.merchantId,
            searchChannel: 'app_stock_merchant_car',
            userId: Constant.userInfo.userId,
        }

        HttpUtils.postRequest(HttpUrls.searchCars, param)
            .then((result) => {
                if (refresh) {
                    this.setState({ dataArray: [] })
                }
                let data = result.data
                if (data) {
                    let resultList = data.resultList
                    let dataBlob = [];
                    let i = itemNo;
                    if (resultList && resultList != null && resultList.length > 0) {
                        resultList.map(function (item) {
                            dataBlob.push({
                                key: i,
                                value: item,
                            })
                            i++;
                        });
                        itemNo = i;
                        this.setState({
                            dataArray: this.state.dataArray.concat(dataBlob),
                            isRefresh: false,
                            showFoot: 1,
                        });
                        setTimeout(() => {
                            this.setState({
                                showFoot: dataBlob.length >= pageSize ? 0 : 1,
                            })
                            resultList = null;
                            dataBlob = null;
                        }, 200);
                    } else {
                        this.setState({
                            showFoot: 1,
                            isRefresh: false,
                        });
                    }
                } else {
                    this.setState({
                        showFoot: 1,
                        isRefresh: false,
                    });
                }
            })
            .catch((error) => {

            });
    }

    insertVcode(vcode) {
        let param = {
            carId: this.state.insertItem.carId,
            vcode: vcode,
            operator: Constant.userInfo.fullname,
        }
        HttpUtils.getRequest(HttpUrls.insertVcodeByCarId, param)
           .then((result) => {
                if (result.code == 0) {
                    let item = this.state.insertItem
                    item.vcode = vcode
                    if (this.props.route.params.completion) {
                        this.props.route.params.completion(item)   
                    }
                }
           })
    }

}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: '#F9F9F9',
    },

    itemContain: {
        marginTop: 10,
        paddingVertical: 10,
        paddingHorizontal: 16,
        width: '100%',
        height: 114,
        backgroundColor: '#fff',
        flexDirection: 'row',
        justifyContent: 'flex-start',
        alignItems: 'center'
    },

    header: {
        width: '100%',
        height: 10,
    },

    carImg: {
        width: 130,
        height: 90,
        borderRadius: 4,
    },
    rightItemBox: {
        flex: 1,
        marginLeft: 10,
        height: '100%',
        paddingVertical: 10,
        flexDirection: 'column',
        justifyContent: 'space-between',
        alignItems: 'flex-start',
    },
    brandText: {
        fontSize: 14,
        color: '#333333',
        fontWeight: '500'
    },
    dateText: {
        marginTop: 8,
        fontSize: 12,
        color: '#999999',
    },
    vinText: {
        marginTop: 8,
        fontSize: 12,
        color: '#333',
    },
    vin1Text: {
        marginTop: 8,
        fontSize: 14,
        color: 'red',
    },

    footer: {
        flexDirection: 'row',
        height: 40,
        justifyContent: 'center',
        alignItems: 'center',
        backgroundColor: '#f6f6f6'
    },
    loadMoreTextStyle: {
        fontSize: 14,
        color: '#999999',
        marginStart: 10,
    },
})